import json
from multiprocessing.dummy import Pool
# -*- coding: utf-8 -*-

from icd_api.icd11 import release_data


def extract_uid_from_url(url):
    uid = url.split('/')[-1]
    if uid.isdigit():
        return uid
    return None


def extract_info(response):
    item = {}

    name = response['title']['@value']
    code = response['code'] if 'code' in response else ''
    class_kind = response['classKind'] if 'classKind' in response else ''

    child = []

    if 'child' in response and len(response['child']) > 0:
        uid_list = []
        for i in response['child']:
            uid = extract_uid_from_url(i)
            if uid is not None:
                uid_list.append(uid)
        child = uid_list
        print(child)
        if len(uid_list) > 0:
            n_CPUs = len(uid_list)
            with Pool(n_CPUs) as p:
                results = p.map(release_data, uid_list)
                for re in results:
                    print(re)
                    if re is not None:
                        extract_info(re)
                    else:
                        print("NoneType is occurred!")

    parent = []
    if 'parent' in response and len(response['parent']) > 0:
        for i in response['parent']:
            uid = extract_uid_from_url(i)
            if uid is not None:
                parent.append(uid)

    index_term = []
    if 'indexTerm' in response and len(response['indexTerm']) > 0:
        for i in response['indexTerm']:
            index_term.append(i['label']['@value'])

    item['name'] = name
    item['uid'] = extract_uid_from_url(response['@id'])
    item['code'] = code
    item['class_kind'] = class_kind
    item['child'] = child
    item['parent'] = parent
    item['index_term'] = index_term

    fout.write(json.dumps(item, ensure_ascii=False))
    fout.write(',\n')

    # termination condition
    return None


if __name__ == '__main__':
    fout = open('data/icd11_2020_10_backup.json', "w", encoding='utf-8')
    fout.write('[')
    extract_info(release_data(icd11_code=''))
    fout.write(']')
    fout.close()
